package com.kgc.stuinfo.stuinfomanagerservice.service;

import com.alibaba.fastjson.JSON;
import com.kgc.stuinfo.bean.Studentinfo;


import com.kgc.stuinfo.config.RedisUtil;
import com.kgc.stuinfo.service.StuService;
import com.kgc.stuinfo.stuinfomanagerservice.mapper.StudentinfoMapper;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RedissonClient;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;

@Service
public class StuServiceImpl implements StuService {
    @Resource
    StudentinfoMapper studentinfoMapper;
    @Resource
    RedissonClient redissonClient;

    @Resource
    RedisUtil redisUtil;
    @Override
    public List<Studentinfo> getAll() {
        List<Studentinfo> studentinfos = studentinfoMapper.selectByExample(null);

        return studentinfos;
    }

    @Override
    public Studentinfo getStuById(Integer id) {
        String key="stu:"+id+":info";
        System.out.println("打印key:"+key);
        Jedis jedis = redisUtil.getJedis();
        String stuinfojson=jedis.get(key);
        Studentinfo studentinfo =null;
        System.out.println("看看键"+stuinfojson);
        if(stuinfojson!=null){
         //缓存里面有
            if(stuinfojson.equals("empty")){
              return null;
            }
            studentinfo = JSON.parseObject(stuinfojson, Studentinfo.class);
        }else{
            //缓存里面没有
            Lock lock =redissonClient.getLock("lock");
            try {
                //上锁
                lock.lock();
                studentinfo = studentinfoMapper.selectByPrimaryKey(id);
                if(studentinfo!=null){
                    String toJSONString = JSON.toJSONString(studentinfo);
                    Random random=new Random();
                    int i = random.nextInt(10);
                    jedis.setex(key,i*60*1000,toJSONString);
                }else{
                    jedis.setex(key,5*60*1000,"empty");
                }
            }catch (Exception e){
                e.getMessage();
            }finally {
                lock.unlock();
            }
        }
        return studentinfo;
    }

    @Override
    public Integer upStu(Studentinfo studentinfo) {
        return studentinfoMapper.updateByPrimaryKeySelective(studentinfo);
    }
}
